from flask import views, render_template, request, url_for, \
    redirect, Blueprint, make_response
import json
from mysql_config import db
from models import Car
from result import Result
from result_code import Code

ct = Blueprint('ct', __name__)


@ct.route('/control', methods=['POST'])
def control():
    cid = request.json.get("cid")
    data = request.json.get("control_data")

    
    car = Car.query.filter(Car.car_id == cid).first()
    if car is None:
        return vars({Result(Code.UPDATE_ERR.value, None, "该配送车不存在")})

    car.control_data = data
    db.session.commit()
    return vars(Result(Code.UPDATE_OK.value, None, data))


@ct.route('/control/<int:cid>', methods=['GET'])
def get_control(cid):
    car = Car.query.filter(Car.car_id == cid).first()
    if car is None:
        return vars({Result(Code.GET_ERR.value, None, "该配送车不存在")})

    return vars(Result(Code.GET_ERR.value, car.control_data, '查询成功'))


